package com.bw.mvi.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import java.lang.reflect.ParameterizedType

abstract class BaseMviFragment<VDB:ViewDataBinding,VM: BaseViewModel<*, *>>: BaseViewFragment<VDB>() {


    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    //直接通过泛型拿到对应的ViewModel的class,来进行实例化
    protected val vm: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        lifecycleScope.launch {
            vm.state.collect {
                when (it) {
                    is UiState.onError -> {
                        failureData(it.msg)
                    }
                    UiState.onLoading -> {

                    }
                    is UiState.onSuccess<*> -> {
                        successData(it)
                    }
                }
            }
        }

        return super.onCreateView(inflater, container, savedInstanceState)
    }
    abstract fun successData(it: UiState.onSuccess<*>)
    abstract fun failureData(error: String)


}